import { Component } from 'react';
import { Group, TextField, TextareaField, Datetime, SelectField, Button,Toast, Boxs, Field } from 'saltui';
const {HBox,Box} = Boxs;
import './PageHome.less';
import AngleRight from 'salt-icon/lib/AngleRight';
import DB from '../../../app/db';
import DragProgressBar from '../../../components/drag-progress-bar';
import CheckedBox from '../../../components/ddCheckboxField';
const {
	Count
} = TextareaField;
const remindTimeData = [
  { value: 1, text: '提前一天' },
  { value: 2, text: '提前两天' },
  { value: 0, text: '不提醒' }
];

export default class PageHome extends Component {
  constructor(props) {
    super(props);

    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    //禁用ios弹性事件
    dd.ui.webViewBounce.disable();
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    var homeHeight = '';
    if(isAndroid==true){
        homeHeight = window.screen.height-44-52-20;
    }else if(isiOS==true){
        homeHeight = window.screen.availHeight-44-52;
    }else {
        if(window.screen.availHeight) {
            homeHeight = 550;
        }
    }

    this.state = {
      id: props.params.id,
      applyRecordId: props.params.applyRecordId,
      title:'',
      endTime: new Date().format("yyyy-MM-dd"),
      endSelect: {},
      responseUserData: [],
      responseUser: '',
      content: '',
      progress: 0,
      remindTimeData: remindTimeData,
      remindTime: remindTimeData[0],
      remindTypeData: [],
      isShowRemindType: false,
      recordName: '',
      limitDataUsers: [],
      comDetails: '',
      homeHeight: homeHeight,
      responseUserName: ''
    }

    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    var isHelpNew = 1;
    dd.util.domainStorage.getItem({ //帮助按钮
       name:'meeting_helpNew_'+userId , // 存储信息的key值
       onSuccess : function(info) {
            var helpNew = info.value;
            if( typeof(helpNew) == 'undefined' || helpNew == '' ){
              isHelpNew = 2;
            }
            //初始化按钮
            t.initButton(isHelpNew);
       },
       onFail : function(err) {
            //alert(JSON.stringify(err));
       }
    });
  }

  //初始化按钮
  initButton(isHelpNew){
    //设置帮助
    /*dd.biz.navigation.setIcon({
        showIcon : true,//是否显示icon
        iconIndex : isHelpNew,//显示的iconIndex,如上图
        onSuccess : function(result) {
            location.hash='help/help_index';
        },
        onFail : function(err) {
        //jsapi调用失败将会回调此函数
        }
    });*/
  }

  componentDidMount(){
    var id = this.state.id;
    var title = "新建";
    var editType = "add";
    if(id!="" && id!=undefined && id!=null){
      title = "编辑";
      editType = "edit";
    }
    $("title").text(title);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
          title : title,//控制标题文本，空字符串表示显示默认文本
          onSuccess : function(result) {},
          onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
          title: {
              text: title,
              icon: '',
              actionmenu: {}
          },
      });
    }

    let t = this;
    var paramInfo = {taskInfoId: id, editType: editType, recordId: this.state.applyRecordId};
    DB.SomeModuleAPI.getTaskInfo(paramInfo).then((content) => {
      var taskInfo = content.taskInfo;
      //提醒设置
      var remindType = "";
      if(taskInfo!=undefined && taskInfo!=null){
        remindType = taskInfo.remindType
      }
      var remindTypeData = [];
      var isShowRemindType = true;
      if(content.noticeType != null){
        var noticeType = content.noticeType.split(",");
        for(var i=0; i<noticeType.length; i++){
          var type = noticeType[i];
          var typeName = "";
          if(type == "0"){
            typeName = "短信";
          }else if(type == "1"){
            typeName = "邮件";
          }else{
            typeName = "消息";
          }
          var typeData = {value: type, text: typeName};
          if(remindType==null || remindType==undefined || remindType==""){
            if(type == "2"){
              typeData.checked = true;
            }
          }else if(remindType!=undefined && remindType.indexOf(type)>=0){
            typeData.checked = true;
          }else{
            typeData.checked = false;
          }
          remindTypeData.push(typeData);
        }
      }else{
        isShowRemindType = false;
      }

      var limitDataUsers = content.limitDataUsers;
      //alert(JSON.stringify(limitDataUsers))
      t.setState({
        remindTypeData: remindTypeData,
        recordName: content.recordName,
        isShowRemindType: isShowRemindType
      });

      if(taskInfo!=undefined && taskInfo!=null){
        var endSelect = taskInfo.endTime.split(" ")[0];
        var remindTime = taskInfo.remindTime;
        var remindTimeSelect = {};
        for(var i=0; i<remindTimeData.length;i++){
          if(remindTime == remindTimeData[i].value){
            remindTimeSelect = remindTimeData[i];
          }
        }

        var responseUserData = content.responseUserData;
        var responseUserName = '';
        for(var j=0; j<limitDataUsers.length; j++){
          limitDataUsers[j].checked = false;
          limitDataUsers[j].disable = false;
          for(var i=0; i<responseUserData.length; i++){
            if(responseUserData[i].value == limitDataUsers[j].value){
              limitDataUsers[j].checked = true;
            }
            if(j == 0){
              responseUserName += responseUserData[i].text + ",";
            }
          }
        }
        if(responseUserName != ""){
          responseUserName = responseUserName.substring(0, responseUserName.length-1);
        }
        let _content = "";
        if(taskInfo.content != null) _content = taskInfo.content;
        let _comDetails = "";
        if(taskInfo.comDetails != null) _comDetails = taskInfo.comDetails;
        t.setState({
          title: taskInfo.title,
          endTime: endSelect,
          endSelect: {value: new Date(endSelect).getTime()},
          responseUserData: responseUserData,
          limitDataUsers: limitDataUsers,
          responseUser: taskInfo.responseUser,
          responseUserName: responseUserName,
          content: _content,
          progress: taskInfo.progress,
          remindTime: remindTimeSelect,
          comDetails: _comDetails
        });
      }else{
        for(var i=0; i<limitDataUsers.length; i++){
          limitDataUsers[i].checked = false;
          limitDataUsers[i].disable = false;
        }
        t.setState({
          limitDataUsers: limitDataUsers
        });
      }  
    }).catch((error) => {
    });
  }

  handleTextChange(field, newValue, size) {
    if (newValue.length <= size) {
      this.setState({
        [field]: newValue,
      });
    }
  }

  // 类型改变
  typeChange(field,value){
    this.setState({
      [field]: value,
    });
  }

  //获取联系人
  getResponsePersion(newValue){
    this.setState({
      responseUserData: newValue
    });
  }

  showResponseUser(type,value){
    if(type == '1'){
      this.setState({responseUserData: []});
    }else{
      var userName = '';
      var responseUserData = value;
      for(var i=0;i<responseUserData.length;i++){
        userName += responseUserData[i].text + ",";
      }
      if(userName != ""){
        userName = userName.substring(0, userName.length-1);
      }
      this.setState({
        responseUserName: userName,
        responseUserData: value
      });
    }
  }

  validateText(text, msg){
    if(!(/^([\u4E00-\u9FA5]|\w|\.)+$/).test(text)){
      Toast.show({
        type: 'error',
        content: msg + '请输入中文/字母/数字/下划线/点',
        onHide: function () {}
      });
      return false;
    }else{
      return true;
    }
  }

  //截止日期
  clickEndTime(value){
    this.setState({
      endSelect: value,
      endTime: new Date(value.value).format("yyyy-MM-dd")
    });
  }

  //修改任务进度
  changeProgress(value){
    this.setState({
      progress: value
    }); 
  }

  showSlot(id) {
    this[id].show();
  }

  //保存任务
  saveTaskInfo(){
    //标题
    if (this.state.title=='') {
      Toast.show({
        type: 'error',
        content: '请填写任务标题',
        onHide: function () {}
      });
      return;
    }else if(!this.validateText(this.state.title, '任务标题')){
      return;
    }
    if(this.state.content != null && isEmojiCharacter(this.state.content)){
      Toast.show({
        type: 'error',
        content: '任务内容不支持表情输入',
        onHide: function () {}
      });
      return;
    }
    var taskId = this.state.id;
    if(this.state.endTime == null || this.state.endTime == ''){
      Toast.show({
        type: 'error',
        content: '请选择截止日期',
        onHide: function () {}
      });
      return;
    }else if(taskId=='' || taskId == null || taskId==undefined){
      let now = new Date().format("yyyy/MM/dd");
      let nowDateTime = new Date(now).getTime();
      let end = this.state.endSelect.value;
      if(nowDateTime > end){
        Toast.show({
          type: 'error',
          content: '截止日期不能小于当前日期',
          onHide: function () {}
        });
        return;
      }
    }

    // 提醒时间
    let remindTime = '';
    let remindType = '';
    if (this.state.remindTime != null) {
        remindTime = this.state.remindTime.value;
        if(remindTime != '0'){
          remindType = '2';
        }
    }

    // 提醒方式
    /*let remindType = '';
    if (this.state.remindTypeData != null) {
      var remindTypeData = this.state.remindTypeData;
      for(var i=0; i<remindTypeData.length;i++){
        if(remindTypeData[i].checked){
          remindType += remindTypeData[i].value + ",";
        }
      }
      if(remindType!=""){
        remindType = remindType.substring(0,remindType.length-1);
      }
    }*/

    let responseUser = '';
    var responseUserData = this.state.responseUserData;
    if (responseUserData!=null && responseUserData!=undefined) {
      for(var i=0; i<responseUserData.length; i++){
        var value = responseUserData[i].value;
        responseUserData[i].checked = true;
        if(value!=null && value!=''){
          responseUser += value + ",";
        }
      }
      if(responseUser != ""){
        responseUser = responseUser.substring(0, responseUser.length-1);
      }
    } 
    if(responseUser=='' || responseUser==null || responseUser==undefined){
      Toast.show({
        type: 'error',
        content: '请选择负责人',
        onHide: function () {}
      });
      return;
    }

    let param = {
      id: this.state.id,
      title: this.state.title,
      content: this.state.content,
      endTime: this.state.endTime,
      responseUser: this.state.responseUser,
      responseUserData: responseUser,
      remindTime: remindTime,
      remindType: remindType,
      progress: this.state.progress,
      applyRecordId: this.state.applyRecordId,
      comDetails: this.state.comDetails
    }
    let id = this.state.id;
    DB.SomeModuleAPI.saveTaskInfo({message: JSON.stringify(param)}).then((content) => {
      Toast.show({
        type: 'success',
        content: '保存成功'
      });

      //返回至列表页面
      setTimeout(function(){
        if(id=="" || id==null || id==undefined){
          history.back();
        }else{
          history.go(-2);
        }
      },2000);
    }).catch((error) => {
      if(typeof(error.errorMsg) == 'undefined'){
        Toast.show({
          type: 'error',
          content: '保存出错'
        });
      }else{
        Toast.show({
          type: 'error',
          content: error.errorMsg
        });
      }
    }); 
  }
  
  render() {
    const angleIconProps = { fill: 'rgba(31,56,88,0.40)', width: 20, height: 20 };
    var viewType = 'add';
    if(this.state.id!="" && this.state.id!=undefined){
      viewType = 'edit';
    }
    
    return (
      <div>
      <div className="page-add">
        <Group.List >
          <TextField required label="任务标题" placeholder="请输入任务标题" value={this.state.title}
            onChange={(value) => { this.handleTextChange('title', value, 20); }} >
          <Count total={20} length={this.state.title.length} /></TextField>
        </Group.List>
        <Group.List >
          <TextareaField label="任务内容" minRows={4} maxRows={7} placeholder="请输入任务内容"
            value={this.state.content} onChange={(value) => { this.handleTextChange('content', value, 200); }} >
            <Count total={200} length={this.state.content.length} /></TextareaField>
        </Group.List>
        <div className={viewType=='edit'?'':'t-DN'}>
          <Group.List>
            <Field label="进度" layout="v">
              <DragProgressBar progressValue={this.state.progress} onChange={this.changeProgress.bind(this)}/>
            </Field>
          </Group.List>
          <div className="t-BCf7 t-H10"></div>
          <Group.List>
            <TextareaField label="任务记录" minRows={4} maxRows={7}
              placeholder="请输入任务记录"
              value={this.state.comDetails}
              onChange={(value) => { this.handleTextChange('comDetails', value, 200); }}
            ><Count total={200} length={this.state.comDetails.length} /></TextareaField>
          </Group.List>
        </div>
        <div className="t-BCf7 t-H10"></div>
        <HBox className="t-field-box t-FBAC t-BCf dd-top-border">
          <div className="t-field-layout-h-label t-FS16 required">截止日期</div>
          <HBox flex="1" onClick={() => {this.showSlot('endSlot')}} className="t-FBAC">
            <Box flex="1"><span className="t-FL t-FS16">{this.state.endTime}</span></Box>
            <Box className="t-FBAC t-field-icon">
              <AngleRight  width={20}  fill="#ccc"/>
              <Datetime locale="zh-cn" slotRef={(s) => this.endSlot = s} title="日期选择" value={this.state.endSelect} 
                columns={Datetime.YMD} onConfirm={(value) => { this.clickEndTime(value); }} />
            </Box>
          </HBox>          
        </HBox>
        <Group.List >
          <TextField required label="所属会议" readOnly={true} value={this.state.recordName} />
        </Group.List>  
        <div className="t-BCf7 t-H10"></div>
        <Group.List>
          <CheckedBox showType='0' required label="负责人" placeholder="请输入用户名称" data={this.state.limitDataUsers}
            placeholderSelect="请选择负责人" onChange={this.showResponseUser.bind(this, "0")} value={this.state.responseUserData}/>
        </Group.List>
        <Group.List className={this.state.isShowRemindType ? '':'t-DN'}>
          <SelectField label="到期提醒" options={remindTimeData} value={this.state.remindTime}
            onSelect={this.typeChange.bind(this,'remindTime')} />
        </Group.List>
      </div>
        <Button.Group>
          <Button type="primary" display="inline" onClick={this.saveTaskInfo.bind(this)}>保存任务</Button>
        </Button.Group>
      </div>
    );
  }
}

